package newsDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
	public NewsUser login(String u, String p) {
		java.sql.PreparedStatement st = null;
		Connection con = null;
		ResultSet rs = null;
		NewsUser nu = new NewsUser();
		con = NewsJDBCUtils.getConnection();
		String sql = "select * from news_users where uname=? and upwd=?";
		try {
			st = con.prepareStatement(sql);
			st.setString(1, u);
			st.setString(2, p);
			rs = st.executeQuery();
			if (rs.next()) {
				nu.setUname(rs.getString("uname"));
				nu.setUpwd(rs.getString("upwd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return nu;
	}

	public int add(NewsUser u) {
		PreparedStatement st = null;
		Connection con = null;
		ResultSet rs = null;
		int r = 0;
		con = NewsJDBCUtils.getConnection();
		String sql = "insert into news_users (uname,upwd) values (?,?)";
		try {
			st = con.prepareStatement(sql);
			st.setString(1, u.getUname());
			st.setString(2, u.getUpwd());
			r = st.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return r;

	}
}
